package com.slz.crm.common.untils;

import com.slz.crm.common.exiception.ServiceException;
import com.slz.crm.pojo.ao.ApprovalAttachmentAO;
import com.slz.crm.pojo.dto.ApprovalAttachmentDTO;
import com.slz.crm.pojo.entity.ApprovalAttachmentEntity;
import com.slz.crm.pojo.vo.ApprovalAttachmentVO;
import com.slz.crm.server.constant.MessageConstant;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
public class IOUtils {

    //存储位置
    private static String filePath;

    @Value("${slz.file.path}")
    public void setFilePath(String filePath) {
        IOUtils.filePath = filePath;
    }

    //文件/符号
    private final static String fileSeparator = File.separator;

    private static File getFileByDTO(ApprovalAttachmentDTO dto) {

        if (dto.getApprovalId() == null || dto.getFileName() == null || dto.getFileType() == null) {
            throw new ServiceException(MessageConstant.FILE_APPROVAL_ID_ERROR);
        }

        return new File(filePath+ fileSeparator + dto.getApprovalId() + fileSeparator
                + dto.getFileName());
    }

    private static File getFilePathByDTO(ApprovalAttachmentDTO dto) {
        if (dto.getApprovalId() == null || dto.getFileName() == null || dto.getFileType() == null) {
            throw new ServiceException(MessageConstant.FILE_APPROVAL_ID_ERROR);
        }

        return new File(filePath+ fileSeparator + dto.getApprovalId() + fileSeparator);
    }

    private static File getFileByEntity(ApprovalAttachmentEntity entity) {
        if (entity.getApprovalId() == null || entity.getFileName() == null || entity.getFileType() == null) {
            throw new ServiceException(MessageConstant.FILE_APPROVAL_ID_ERROR);
        }


        return new File(filePath+ fileSeparator + entity.getApprovalId() + fileSeparator
                + entity.getFileName());
    }

    /**
     * 写入文件
     * @param dto  文件信息
     * @return  文件实体
     */
    public static ApprovalAttachmentEntity writeFile(ApprovalAttachmentDTO dto) {

        ApprovalAttachmentEntity attachment = new ApprovalAttachmentEntity();

        try {
            File file = getFileByDTO(dto);

            File parentDir = file.getParentFile();
            if (!parentDir.exists()) {
                // 递归创建多级目录
                boolean mkdirsSuccess = parentDir.mkdirs();
                if (!mkdirsSuccess) {
                    throw new IOException("无法创建目录: " + parentDir.getAbsolutePath());
                }
            }


            MultipartFile fileData = dto.getFileData();
            if(fileData != null){
                fileData.transferTo(file);
            }

            BeanUtils.copyProperties(dto, attachment);
            //设置文件类型
            if (fileData != null) {
                attachment.setFileType(fileData.getContentType());
            }
            //设置文件路径
            if (fileData != null) {
                attachment.setFilePath(filePath + fileSeparator + dto.getApprovalId() + fileSeparator);
            }
            //设置文件大小
            if (fileData != null) {
                attachment.setFileSize(fileData.getSize());
            }

            return attachment;
        } catch (IOException e) {
            throw new ServiceException(MessageConstant.FILE_CREATE_ERROR,e);
        }
    }

    /**
     * 删除文件
     * @param entity 文件实体
     * @return 是否成功
     */
    public static Boolean deleteFile(ApprovalAttachmentEntity entity) {
        if(entity != null && entity.getFilePath() != null){
            File file = getFileByEntity(entity);
            if(file.exists()){
                if(!file.delete())
                    throw new ServiceException(MessageConstant.FILE_DELETE_ERROR);
            }
        }
        return true;
    }

    public static Boolean deleteFile(List<ApprovalAttachmentEntity> entitys) {
        if(entitys != null && !entitys.isEmpty()){
            for (ApprovalAttachmentEntity entity : entitys) {
                deleteFile(entity);
            }
        }
        return true;
    }

    /**
     * 获取文件字节
     * @param entity 文件实体
     * @return 文件字节
     */
    public static ApprovalAttachmentVO getOneFileBytes(ApprovalAttachmentEntity entity) {

        try {
            FileInputStream fis = new FileInputStream(getFileByEntity(entity));
            byte[] bytes = new byte[fis.available()];
            int read = fis.read(bytes);
            if(read != bytes.length)
                throw new ServiceException(MessageConstant.FILE_READ_ERROR);
            fis.close();

            ApprovalAttachmentVO vo = new ApprovalAttachmentVO();

            vo.setFileData(bytes);
            BeanUtils.copyProperties(entity,vo);
            return vo;
        } catch (IOException e) {
            throw new ServiceException(MessageConstant.FILE_READ_ERROR,e);
        }

    }


    public static List<ApprovalAttachmentVO> readFile(List<ApprovalAttachmentEntity> entityList) {

        List<ApprovalAttachmentVO> voList = new ArrayList<>();
        if(entityList != null && !entityList.isEmpty()){
            for (ApprovalAttachmentEntity entity : entityList) {
                ApprovalAttachmentVO vo = getOneFileBytes(entity);

                BeanUtils.copyProperties(entity,vo);

                voList.add(vo);
            }
        }

        return voList;
    }




}
